package com.woniuxy.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.entity.OperationLog;
import com.woniuxy.service.OperationLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLOutput;
import java.sql.Timestamp;


@Component//对象放到Spring容器中，并且要扫描到这个包
@Aspect //这是一个切面类
public class OperationLogAspect {
    @Autowired
    private OperationLogService operationLogService;

    /**
     * 使用环境通知实现计时功能
     * 拦截员工对象的方法对其进行监控放行
     */
//    @Around("execution(public * com.woniuxy.service.CarMaintenanceService.*(..))")
    //使用注解方式
    @Around("@annotation(com.woniuxy.aspect.LogRecord)")
    public Object OperationLogTimerKeeping(ProceedingJoinPoint joinPoint) throws Throwable {

        Object result;
        //获取现在时间
        long begin = System.currentTimeMillis();
        //调用目标方法，若没执行就会拦截
        result = joinPoint.proceed();
        //再计时
        long end = System.currentTimeMillis();
        //耗时
        long executionTime = end - begin;
        //获取目标信息
        Signature signature = joinPoint.getSignature();
        //获取方法名
        String methodName = signature.getName();
        //参数
        Object[] args = joinPoint.getArgs();

        //ObjectMapper mapper = new ObjectMapper();
        String methodParams = "";
        for (Object arg : args) {
            String s = String.valueOf(arg);
            methodParams += s;
        }
        System.out.println("方法参数" + methodParams);
        //返回值
        String resultValue;
        if (result == null) {
            resultValue = "void";
        } else {
            resultValue = String.valueOf(result);
        }
        //操作时间
        Timestamp logTime = new Timestamp(System.currentTimeMillis());
        //创建新对象
        OperationLog operationLog = new OperationLog(null, methodName, methodParams, executionTime, resultValue, logTime);
        //调用业务层写到数据库中
        operationLogService.addOperationLog(operationLog);
        return result;
    }
}
